<template>
  <div class="app-container">
    <el-form
      ref="form"
      class="form"
      :rules="rules"
      :model="form"
      label-width="80px"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>

       <el-form-item label="销售平台" prop="sellType">
        <el-select
          style="width: 100%"
          v-model="form.sellType"
          placeholder="请选择销售平台"
          @change="productFormTypeFn"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in productFormTypeList"
            :key="item.value"
            
          ></el-option>
        </el-select>
      </el-form-item>


        <el-form-item label="选择品牌" prop="brandId">
        <el-select
          style="width: 100%"
          v-model="form.brandId"
          placeholder="请选择品牌"
          @change="brandIdFn"
        >
          <el-option
            :label="item.brandName"
            :value="item.id"
            v-for="item in brandList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>



      <el-form-item label="appSkuId" prop="appSkuId" v-if="form.sellType=='2'">
        <el-input
          v-model="form.appSkuId"
          placeholder="请输入appSkuId"
        ></el-input>
      </el-form-item>

      <el-form-item label="店铺" prop="shopId">

           <el-select
          style="width: 100%"
          v-model="form.shopId"
          placeholder="请选择店铺"
        >
          <el-option
            :label="item.shopName"
            :value="item.id"
            v-for="item in shopList"
            :key="item.id"
          ></el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="清洗类型" prop="washType">
        <el-select
          style="width: 100%"
          v-model="form.washType"
          placeholder="请选择洗鞋类型"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in washTypeList"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品分类" prop="typeId">
        <el-select
          style="width: 100%"
          v-model="form.typeId"
          placeholder="请选择商品分类"
        >
          <el-option
            :label="item.typeName"
            :value="item.id"
            v-for="item in categoryList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

     

      <el-form-item label="商品价格" prop="price">
        <el-input v-model="form.price" placeholder="请输入商品价格"></el-input>
      </el-form-item>

      <el-form-item label="商品原价" prop="oriPrice">
        <el-input
          v-model="form.oriPrice"
          placeholder="请输入商品原价"
        ></el-input>
      </el-form-item>

      <el-form-item label="鞋子数量" prop="shoesNum">
        <el-input
          v-model="form.shoesNum"
          placeholder="请输入鞋子数量"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="商品图片"
        prop="url"
        :rules="[
          { required: true, message: '请上传商品图片', trigger: 'change' },
        ]"
      >
        <el-upload
          :action="`${BASE_URL}/common/images/upload`"
          accept="image/jpeg,image/jpg,image/png"
          list-type="picture-card"
          :class="{ disabled: uploadDisabled }"
          :file-list="urlPictureList"
          :on-remove="handleProductUploadChange"
          :on-change="handleProductUploadChange"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item
        label="轮播图片"
        prop="bannerUrl"
        :rules="[
          { required: true, message: '请上传轮播图片', trigger: 'change' },
        ]"
      >
        <el-upload
          :action="`${BASE_URL}/common/images/upload`"
          accept="image/jpeg,image/jpg,image/png"
          list-type="picture-card"
          :file-list="bannerPictureList"
          :on-remove="handleBannerUploadChange"
          :on-change="handleBannerUploadChange"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item
        label="详情图片"
        prop="detailUrl"
        :rules="[
          { required: true, message: '请上传详情图片', trigger: 'change' },
        ]"
      >
        <el-upload
          :action="`${BASE_URL}/common/images/upload`"
          accept="image/jpeg,image/jpg,image/png"
          list-type="picture-card"
          :file-list="detailPictureList"
          :on-remove="handleDetailUploadChange"
          :on-change="handleDetailUploadChange"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品备注">
        <el-input
          type="textarea"
          v-model="form.remark"
          placeholder="请输入商品备注"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{
          form.id ? "保存修改" : "立即创建"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getShopGoodDetail,
  addOrEditShopGood,
  getProductCategories,
} from "@/api/product/index";
import { washTypeList, productFormTypeList  , productFormTypeListDic } from "@/config/index";
import { BASE_URL, IMAGE_OSS_URL } from "@/config/index";

import { listBrand } from "@/api/brand/index";
import {
  getShopList
} from "@/api/shop/index";
export default {
  data() {
    return {
      BASE_URL,
      IMAGE_OSS_URL,
      queryShopParams:{
        brandId:"",
        channel:""
      },

      shopList:[],
      form: {
        name: "",
        price: "",
        shoesNum: "",
        remark: "",
        washType: "",
        appSkuId: "",
        oriPrice: "",
        typeId: "",
        url: "",
        sellType: "",
        bannerUrl: "",
        detailUrl: "",
        shopId:""
      },
      productFormTypeList,
      categoryList: [],
      urlPictureList: [],
      bannerPictureList: [],
      detailPictureList: [],
      brandList:[],
      washTypeList,
      loading: false,
      rules: {
        sellType: [
          { required: true, message: "请选择销售平台", trigger: "blur" },
        ],

         shopId: [
          { required: true, message: "店铺不能空", trigger: "blur" },
        ],
        washType: [
          { required: true, message: "请选择洗鞋类型", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        appSkuId: [
          { required: true, message: "请输入appSkuId", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: "请输入正确的价格",
            trigger: "blur",
          },
        ],
        typeId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        oriPrice: [
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: "请输入正确的价格",
            trigger: "blur",
          },
        ],
        shoesNum: [
          { required: true, message: "请输入鞋子数量", trigger: "blur" },
        ],
        url: [
          { required: true, message: "请上传商品分类图片", trigger: "change" },
        ],
        bannerUrl: [
          { required: true, message: "请上传轮播图片", trigger: "change" },
        ],
        detailUrl: [
          { required: true, message: "请上传详情图片", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    uploadDisabled: function () {
      return this.form.url;
    },
  },
  created() {
    if (this.$route.query.id) {
      this.getDetail();
    }
    this.getProductCategories();
    getShopList({}).then(res=>{
      this.shopList=res.data.records

    })
  },
  methods: {

    brandIdFn(){
      // console.info("品牌选择")
      this.shopList=[]
      this.form.shopId=""
      getShopList({...this.queryShopParams,brandId:this.form.brandId}).then(res=>{
           this.shopList=res.data.records
      })

    },

     productFormTypeFn(){
      this.shopList=[]
      this.brandList=[]
      this.form.shopId=""
      this.form.brandId=""
      let sellType=this.form.sellType;
      let sellTypeDic=productFormTypeListDic[sellType];
      if(sellTypeDic == 'DY'){
         this.rules.appSkuId=[]
      }
      this.queryShopParams.channel=sellTypeDic
      //根据渠道获取最新的品牌
      listBrand({platformType:sellTypeDic}).then(res=>{
         this.brandList=res.data.records
      })

     },

    getProductCategories() {
      getProductCategories({}, 1, 9999).then((res) => {
        this.categoryList = res.data.records;
      });
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        // console.log(this.form);
        if (valid) {
          this.loading = true;
          addOrEditShopGood({
            ...this.form,
            url: this.urlPictureList
              .map((item) => item.response.data)
              .join(","),
            detailUrl: this.detailPictureList
              .map((item) => item.response.data)
              .join(","),
            bannerUrl: this.bannerPictureList
              .map((item) => item.response.data)
              .join(","),
          })
            .then((res) => {
              this.loading = false;
              this.$message.success("操作成功");
              this.$router.push("/product/list");
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getDetail() {
      getShopGoodDetail(this.$route.query.id).then((res) => {
        this.form = res.data;
        if(this.form.brandId){
          let sellTypeDic=productFormTypeListDic[this.form.sellType];
         //根据渠道获取最新的品牌
          listBrand({platformType:sellTypeDic}).then(res=>{
         this.brandList=res.data.records
           })
          if(this.form.brandId){
              getShopList({...this.queryShopParams,brandId:this.form.brandId}).then(res=>{
              this.shopList=res.data.records
              })
          }

        }
        this.urlPictureList = this.form.url
          ? this.form.url.split(",").map((item) => ({
              url: IMAGE_OSS_URL + item,
              status: "success",
              response: {
                data: item,
              },
            }))
          : [];
        this.bannerPictureList = this.form.bannerUrl
          ? this.form.bannerUrl.split(",").map((item) => ({
              url: IMAGE_OSS_URL + item,
              status: "success",
              response: {
                data: item,
              },
            }))
          : [];
        this.detailPictureList = this.form.detailUrl
          ? this.form.detailUrl.split(",").map((item) => ({
              url: IMAGE_OSS_URL + item,
              status: "success",
              response: {
                data: item,
              },
            }))
          : [];
      });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isLt2M;
    },
    handleProductUploadChange(file, fileList) {
      this.urlPictureList = fileList;
      this.form.url = fileList.map((item) => item.url).join(",");
    },
    handleBannerUploadChange(file, fileList) {
      this.bannerPictureList = fileList;
      this.form.bannerUrl = fileList.map((item) => item.url).join(",");
    },
    handleDetailUploadChange(file, fileList) {
      this.detailPictureList = fileList;
      this.form.detailUrl = fileList.map((item) => item.url).join(",");
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  width: 480px;
}
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
